const {Menu, Op} = require('../db/seq')

class MenuServe {
    async addMenuServe(ctx) {
        const {name, level, pid, code, route} = ctx.request.body;
        const {id: createdByUserId} = ctx.state.user;
        const res = await Menu.findOne({
            where: {
                name,
            }
        })
        if (res && res.dataValues) {
            throw ({message: '已存在'})
        } else {
            const res = await Menu.create({
                name,
                type: level === 4 ? 2 : 1,
                level,
                pid,
                code,
                select: false,
                route,
                createdByUserId
            });
            return res.dataValues;
        }
    }

    async getMenuServe(menuId) {
        const res = await Menu.findAll({
            attributes: {exclude: ['deletedTime', 'createdByUserId']},
            where: menuId ? {
                id: typeof menuId !== "number" && menuId.split(',').length > 1 ? {
                    [Op.or]: menuId.split(',')
                } : menuId
            } : {}
        });
        return res ? res : null;
    }

    async getMenuById(id) {
        const res = await Menu.findOne({
            attributes: {exclude: ['deletedTime', 'createdByUserId']},
            where: {
                id
            }
        })
        return res ? res.dataValues : null
    }

    async updateMenuServe(ctx, id) {
        const {name, level, pid, code, route} = ctx.request.body;
        const {id: createdByUserId} = ctx.state.user;
        const res = await Menu.update({
            name,
            level,
            pid,
            code,
            route,
            createdByUserId
        }, {
            where: {id}
        });
        // console.log(res);  [1]
        return res[0] > 0;
    }

    async deleteMenuServe(id) {
        const res = await Menu.destroy({
            where: {
                id
            }
        });
        return res > 0;
    }
}

module.exports = new MenuServe();
